package com.bw.module_video_detail.test_mediaplayer

import android.graphics.SurfaceTexture
import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import android.view.Surface
import android.view.TextureView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bw.module_video_detail.R

/**
 * mediaPlayer+TextureView：视频播放
 */
class TextureActivity : AppCompatActivity(), TextureView.SurfaceTextureListener {
    private lateinit var textureView: TextureView
    private lateinit var mediaPlayer: MediaPlayer
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_texture)
        textureView = findViewById(R.id.texture_view)
        initPlayer()
        initTexture()
        //视频旋转
        textureView.rotation = 90f

    }

    private fun initTexture() {
        textureView.surfaceTextureListener = this
    }

    private fun initPlayer(){
        mediaPlayer = MediaPlayer()
        mediaPlayer.setDataSource("http://txmov2.a.yximgs.com/upic/2020/08/23/20/BMjAyMDA4MjMyMDU3MzVfNDc1MTQ4NzZfMzQ4NzcwMzIxOTlfMV8z_b_B09a31110bdc2b61828d27ef27390ecec.mp4?tag=1-1599270586-vdg-1-h2fj3f9rtd-6b0b801241e3b41e&tt=b&bp=10000")
        mediaPlayer.prepareAsync()
        mediaPlayer.setOnPreparedListener {
            mediaPlayer.start()
        }
    }

    override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
        Log.d("TAG", "onSurfaceTextureAvailable: ")
        mediaPlayer.setSurface(Surface(surface))
    }

    override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
        Log.d("TAG", "onSurfaceTextureSizeChanged: ")
    }

    override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
        Log.d("TAG", "onSurfaceTextureDestroyed: ")
        mediaPlayer.release()
        return true
    }

    override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
        Log.d("TAG", "onSurfaceTextureUpdated: ")
    }

}